<template>
  <div class="app-container flex column">
    <top-title :updateTime="true" :content="content"></top-title>

    <div class="tree-from-wrap f1 min-height-0 flex">
      <div class="left-tree-wrap f1 flex column min-height-0">
        <div class="alter flex align-center">
          <img src="@/assets/imgs/alter_icon.png" alt="" />
          <span>当前选择:</span>
          <span v-if="currSelected.id">{{ currSelected.departName }}</span>
          <span v-if="currSelected.id" @click="onClearSelected">取消选择</span>
        </div>

        <div class="search-group" style="padding: 0 0.1rem 0 0.2rem">
          <div class="input-wrap" style="width: 100%">
            <div class="input-item" style="padding: 0; width: 100%">
              <a-input v-model="value" @pressEnter="onSearch" :maxLength="15" placeholder="请输入区域名称">
                <a-icon class="search-icon" slot="prefix" type="search" />
                <a-button @click="onSearch" slot="suffix" type="primary" class="searchBtn" style="margin-right: 0"
                  >搜索</a-button
                >
              </a-input>
            </div>
          </div>
        </div>

        <div class="tree-wrap f1" style="height: 100%; padding: 0 0.2rem; overflow: scroll">
          <a-tree
            multiple
            checkable
            :loading="loading"
            :selectedKeys="selectedKeys"
            :checkedKeys="checkedKeys"
            :treeData="departTree"
            :expandedKeys="iExpandedKeys"
            :checkStrictly="checkStrictly"
            :autoExpandParent="autoExpandParent"
            :replace-fields="replaceFields"
            @check="onCheck"
            @select="onSelect"
            @expand="onExpand"
          >
            <a-icon slot="switcherIcon" type="down" />
            <template #title="{ departName }">
              <span v-if="departName.indexOf(value) > -1">
                {{ departName.substr(0, departName.indexOf(value)) }}
                <span style="color: #ecf0f1; background: #74b9ff">{{ value }}</span>
                {{ departName.substr(departName.indexOf(value) + value.length) }}
              </span>
              <span v-else>{{ departName }}</span>
            </template>
          </a-tree>

          <div class="drawer-bootom-button">
            <a-dropdown :trigger="['click']" placement="topCenter">
              <a-menu class="much" slot="overlay">
                <a-menu-item key="3" @click="checkALL">全部勾选</a-menu-item>
                <a-menu-item key="4" @click="cancelCheckALL">取消全选</a-menu-item>
                <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
                <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
              </a-menu>
              <a-button class="searchBtn"> 树操作 <a-icon type="up" /> </a-button>
            </a-dropdown>
          </div>
        </div>
      </div>

      <div class="right-form-wrap f1">
        <a-card class="right-form-wrapper" :bordered="false" v-if="selectedKeys.length > 0">
          <a-form-model
            ref="form"
            :model="form"
            :rules="rules"
            class="formStyle"
            autocomplete="off"
            layout="inline"
            :labelCol="{ style: 'width: 100px' }"
          >
            <a-row>
              <a-col :span="24">
                <a-form-model-item label="区域名称">
                  <a-input :maxLength="30" autocomplete="off" :disabled="true" v-model="form.departName" />
                </a-form-model-item>
              </a-col>
            </a-row>

            <a-row>
              <a-col :span="24">
                <a-form-model-item label="国家编码">
                  <a-input :maxLength="30" autocomplete="off" :disabled="true" v-model="form.nationCode" />
                </a-form-model-item>
              </a-col>
            </a-row>

            <a-row>
              <a-col :span="24">
                <a-form-model-item label="上级区域">
                  <a-input :maxLength="30" autocomplete="off" :disabled="true" v-model="form.parantName" />
                </a-form-model-item>
              </a-col>
            </a-row>

            <a-row>
              <a-col :span="23">
                <a-form-model-item label="经度" prop="lng">
                  <a-input
                    :maxLength="30"
                    autocomplete="off"
                    :disabled="true"
                    placeholder="请在地图上选择经纬度"
                    v-model="form.lng"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="1">
                <img
                  @click="showMap"
                  class="select-map-img cursor"
                  style="width: 40px; height: 40px"
                  src="@/assets/imgs/in-map.png"
                />
              </a-col>
            </a-row>

            <a-row>
              <a-col :span="24">
                <a-form-model-item label="纬度" prop="lat">
                  <a-input
                    :maxLength="30"
                    autocomplete="off"
                    :disabled="true"
                    placeholder="请在地图上选择经纬度"
                    v-model="form.lat"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>

            <a-row>
              <a-col :span="24">
                <a-form-model-item label="排序" prop="departOrder">
                  <a-input :maxLength="30" autocomplete="off" placeholder="请输入排序值" v-model="form.departOrder" />
                </a-form-model-item>
              </a-col>
            </a-row>

            <a-row>
              <a-col :span="24">
                <a-form-model-item label="备注">
                  <a-input :maxLength="30" autocomplete="off" placeholder="请输入备注" v-model="form.memo" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>

          <div class="anty-form-btn flex justify-center">
            <a-button @click="emptyCurrForm" class="resetBtn" type="primary" htmlType="button" icon="sync">
              重置
            </a-button>
            <a-button
              @click="submitCurrForm"
              class="searchBtn"
              type="primary"
              htmlType="button"
              icon="form"
              v-has="'office:edit'"
              style="margin-left: 40px"
            >
              保存
            </a-button>
          </div>
        </a-card>
        <a-card :bordered="false" v-else>
          <a-empty>
            <span slot="description"> 请先选择一个区域! </span>
          </a-empty>
        </a-card>
      </div>
    </div>
    <t-map :visible.sync="isShowMap" @getLatLong="getLatLong" ref="tMap"></t-map>
  </div>
</template>

<script>
import topTitle from '@/components/topTitle'
import TMap from '@/components/t-map/index.vue'
import { putAction, httpAction, deleteAction, getAction } from '@/api/manage'
export default {
  name: 'regionalManagement',
  components: { topTitle, TMap },
  data() {
    return {
      content: [['区域管理']],
      loading: false,
      currSelected: {},
      value: '',
      dataList: [],

      departTree: [],
      selectedKeys: [],
      checkedKeys: [],
      iExpandedKeys: [],
      checkStrictly: true,
      replaceFields: {
        key: 'id',
        title: 'departName',
      },
      autoExpandParent: true,
      allTreeKeys: [],

      isShowMap: false,
      form: {},
      rules: {
        lng: [{ required: true, message: '请选择经度!' }],
        lat: [{ required: true, message: '请选择纬度!' }],
        departOrder: [{ required: true, message: '请输入排序值!' }],
        memo: [{ required: true, message: '请输入备注!' }],
      },
    }
  },
  mounted() {
    this.getRegionalList()
  },
  methods: {
    async getRegionalList() {
      this.loading = true
      const { result } = await getAction('/sys/depart/query_tree_list')
      this.departTree = result
      this.getAllKeys(result[0]) // * 用于右下角树操作功能
      this.generateList(this.departTree) // * 用作搜索 书中包含关键字的方法
      this.loading = false
    },

    getAllKeys(node) {
      this.allTreeKeys.push(node.id)
      if (node.children && node.children.length > 0) {
        for (let a = 0; a < node.children.length; a++) {
          this.getAllKeys(node.children[a])
        }
      }
    },
    onExpand(expandedKeys) {
      console.log('onExpand', expandedKeys)
      this.iExpandedKeys = expandedKeys
      this.autoExpandParent = false
    },

    onCheck(checkedKeys, info) {
      let record = info.node.dataRef
      console.log('onCheck-record', record)
      this.currSelected = Object.assign({}, record)
      this.selectedKeys = [record.id]
      if (this.checkStrictly) {
        this.checkedKeys = checkedKeys.checked
      } else {
        this.checkedKeys = checkedKeys
      }
    },

    onSelect(selectedKeys, e) {
      let record = e.node.dataRef
      console.log('onSelect-record', record)
      this.currSelected = Object.assign({}, record)
      this.checkedKeys = [record.id] // ! 设置勾选
      this.selectedKeys = [record.id]
      this.setValuesToForm(record)
    },

    setValuesToForm(record) {
      this.form = { ...record }
      this.form.status = 1
      this.form.parantName = this.findDepartNameById(this.departTree, record.parentId)
      // this.form.id = record.id
      // this.form.departName = record.departName
      // this.form.nationCode = record.nationCode
      // this.form.lng = record.lng
      // this.form.lat = record.lat
      // this.form.departOrder = record.departOrder
      // this.form.memo = record.memo
    },

    findDepartNameById(data, targetId) {
      for (const node of data) {
        if (node.id === targetId) {
          return node.departName
        }
        if (node.children && node.children.length > 0) {
          const departName = this.findDepartNameById(node.children, targetId)
          if (departName !== '暂无') return departName
        }
      }
      return '暂无'
    },

    // ! 清空方法
    onClearSelected() {
      this.checkedKeys = []
      this.currSelected = {}
      this.selectedKeys = []
    },

    onSearch() {
      const expanded = this.dataList
        .map((item) => {
          if (item.departName.indexOf(this.value) > -1) {
            return this.getParentKey(item.id, this.departTree)
          }
          return null
        })
        .filter((item, i, self) => {
          if (item && self.indexOf(item) === i) {
            return item
          }
        })
      this.iExpandedKeys = expanded
      this.autoExpandParent = true
    },
    getParentKey(key, tree) {
      let parentKey
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        if (node.children) {
          if (node.children.some((item) => item.id === key)) {
            parentKey = node.id
          } else if (this.getParentKey(key, node.children)) {
            parentKey = this.getParentKey(key, node.children)
          }
        }
      }
      return parentKey
    },
    generateList(tree) {
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        const id = node.id
        const departName = node.departName
        this.dataList.push({
          id,
          departName: departName,
        })
        if (node.children) {
          this.generateList(node.children)
        }
      }
    },

    // * 右下角 dropdown 功能开始
    checkALL() {
      this.checkStriccheckStrictlytly = false
      this.checkedKeys = this.allTreeKeys
    },
    cancelCheckALL() {
      this.checkedKeys = []
    },
    expandAll() {
      this.iExpandedKeys = this.allTreeKeys
    },
    closeAll() {
      this.iExpandedKeys = []
    },
    // * 右下角 dropdown 功能结束

    showMap() {
      this.isShowMap = true
    },
    getLatLong(value) {
      this.form.lng = value[0]
      this.form.lat = value[1]
    },

    forceUpdate() {
      this.$forceUpdate()
    },

    emptyCurrForm() {
      this.form.lng = ''
      this.form.lat = ''
      this.form.departOrder = ''
      this.form.memo = ''
    },

    submitCurrForm() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return
        const res = await putAction('/sys/depart/edit', this.form)
        if (res.code === 200) {
          this.getRegionalList()
          this.$message.success('编辑成功')
        }
      })
    },
  },
}
</script>

<style scoped lang="less">
/deep/ .ant-card {
  background: var(--theme-container-bg);
  color: #1163b8;
}

.min-height-0 {
  min-height: 0;
  overflow: scroll;
}
.app-container {
  background: var(--theme-content-bg);
  padding-top: 0;
}

.left-tree-wrap {
  position: relative;
  background: var(--theme-container-bg);

  .btn-group {
    padding: 0.2rem 0 0 0.2rem;
    .btn-common {
      width: 1.2rem;
      height: 0.4rem;
      line-height: 0.4rem;
      text-align: center;
      background: #1388ff;
      border-radius: 0.04rem;
      font-size: 0.16rem;
      font-weight: bold;
      color: #0b3f73;
      cursor: pointer;
      &:nth-child(2) {
        margin-left: 0.2rem;
      }
    }
  }

  .drawer-bootom-button {
    position: absolute;
    right: 0.1rem;
    bottom: 0.1rem;
    border-radius: 0.04rem;
  }
}

.right-form-wrap {
  background: var(--theme-container-bg);
  margin-left: 0.2rem;

  .right-form-wrapper {
    height: 7.8rem;
    overflow-y: auto;
  }
}
</style>
